#!/usr/bin/env python

import os
from liwe.module import LiweModule

class StaticPage ( LiweModule ):
	__FIELDS = [ 'id', 'name', 'title', 'visible', 'id_html', 'uid', 'created' ]

	def __init__ ( self, liwe ):
		super ( StaticPage, self ).__init__ ( liwe, "staticpage" )

		self.dbm = self.liwe.dbm

	#=================================================
	# OVERRIDDABLE METHODS
	#=================================================
	def get_manip ( self, row ):
		pass

	def list_manip ( self, row ):
		pass

	#=================================================
	# PUBLIC
	#=================================================


	def get_html_page ( self, page ):
		path = os.path.join ( self.cfg.get ( "text_pages" ), page + ".html" )
		cnt = ""
		if os.path.isfile ( path ):
			cnt = open ( path ).read ()

		return cnt

	def get_static_page_by_name ( self, name ):
		res = { 'html': 'Pagina non disponibile' }
		r = self.dbm.single_row ( "static_page", StaticPage.__FIELDS, "name = '%s' AND visible = 1" % name )
		if r:
			res = r
			res [ 'html' ] = self.liwe.invoke ( "page_manager.ajax.get", r [ 'id_html' ] ) [ 'page' ] [ 'txt' ]

		return res

	def delete ( self, ids ):
		ids = ids.split ( "|" )
		str_ids = " ,".join ( ids )

		rs = self.dbm.select ( "static_page", StaticPage.__FIELDS, "id IN ( %s )" % str_ids )
		for r in rs:
			self.liwe.invoke ( "page_manager.admin.delete", r [ 'id_html' ] )
			self.dbm.delete ( "static_page", "id = %s" % r [ 'id'  ] )

		return True

	def get ( self, id_page ):
		r = self.dbm.single_row ( "static_page", StaticPage.__FIELDS, "id = %s" % id_page )
		r [ 'html' ] = self.liwe.invoke ( "page_manager.ajax.get", r [ 'id_html' ] ) [ 'page' ] [ 'txt' ]

		return r

	def create ( self, html, name, title = '', id_page = None, id_html = 0, visible = 1 ):
		# Inserisco i dati nel page manager
		id_html = self.liwe.invoke ( "page_manager.admin.create", html, id_html, module = 'staticpage' ) [ 'id_page' ]

		name = name.lower()

		uid = self.liwe.pyhp.session.data.get ( "uid", 0 )

		dct = {
			"name": name,
			"title": title,
			"id_html": id_html,
			"visible": visible
		}

		if not id_page:
			dct [ 'created' ] = "*NOW()"
			dct [ 'uid' ] = uid

			r = self.dbm.single_row ( "static_page", StaticPage.__FIELDS, "name = '%s'" % name )
			if r:
				self.liwe.err_code = 1
				self.liwe.err_descr = "Il nome della pagina e' gia' in uso"
				return

			self.dbm.insert ( "static_page", dct )
			id_page = self.dbm.insert_id ()

		else:
			r = self.dbm.single_row ( "static_page", StaticPage.__FIELDS, "name = '%s' AND id <> %s" % ( name, id_page ) )
			if r:
				self.liwe.err_code = 1
				self.liwe.err_descr = "Il nome della pagina e' gia' in uso"
				return

			self.dbm.update ( "static_page", dct, "id = %s" % id_page )


		return id_page

	def list ( self, start_point = 0, limit = 10 ):
		extras = [ " ORDER BY name, created " ]
		if limit:
			extras.append (  " LIMIT %s,%s " % ( start_point, limit ) )

		tables = [ "static_page" ]
		fields = [ "id", "id_html", "created", "name", "title", "visible" ]

		tot_rows = self.dbm.count ( tables, fields )

		cur = self.dbm.select ( tables, fields, extras = " ".join ( extras ) )

		rows = []

		if cur:
			for r in cur:
				self.list_manip ( r )
				rows.append ( r )

			cur.close ()

		return { "rows" : rows, "tot_rows" : tot_rows }

	def search ( self, testo = '', start_pos = 0, limit = 10 ):

		extras = 'ORDER BY name LIMIT %s,%s' % ( start_pos, limit )
		tables = [ 'static_page AS n', 'page AS p' ]
		fields = [ "id", "id_html", "n.created AS created", "name", "title", "visible", 'p.txt as html' ]
		ids = []
		conds = [ 'n.id_html = p.id_page' ]
		pages = self.liwe.invoke ( 'page_manager.ajax.search', testo = testo, module = 'staticpage' ) [ 'pages' ]
		for p in pages:
			ids.append ( str ( p [ 'id_page' ] ) )

		if ids:
			ids = '(' + ','.join ( ids ) + ')'
			conds.append ( '( n.id_html IN %s )' % ids )
		else:
			return { 'rows': [], 'tot_rows': 0 }

		conds = ' AND '.join ( conds )
		tot_rows = self.dbm.count ( tables, fields, conds )
		rows = self.dbm.all_rows ( tables, fields, conds, extras = extras )
		if not rows:
			rows = []

		return { 'rows': rows, 'tot_rows': tot_rows }
